﻿
Namespace LightSwitchApplication

    Public Class Appointment
        Private Sub StartTime_Validate(results As EntityValidationResultsBuilder)
            If Me.StartTime >= Me.EndTime Then
                results.AddPropertyError("Start time cannot be after end time.")
            ElseIf validateTime(Me.StartTime) = False Then
                results.AddPropertyError("An appointment already exists covering your start time.")
            End If
        End Sub

        Private Sub EndTime_Validate(ByVal results As Microsoft.LightSwitch.EntityValidationResultsBuilder)
            If Me.EndTime < Me.StartTime Then
                results.AddPropertyError("End time cannot be before start time.")
            ElseIf validateTime(Me.EndTime) = False Then
                results.AddPropertyError("An appointment already exists covering your end time.")
            End If

        End Sub

        
        Private Sub Customer_Validate(results As EntityValidationResultsBuilder)
            'Set the default location to the customer's address
            If Me.Customer IsNot Nothing AndAlso Me.Location Is Nothing Then
                Me.Location = Me.Customer.FullAddress
            End If

        End Sub

        Private Sub Appointment_Created()
            Me.StartTime = Now
            Me.EndTime = Now.AddHours(1)
        End Sub


        Function validateTime(valDate As Date) As Boolean
            Dim upcomingAppointment = From upcoming In Me.DataWorkspace.ApplicationData.CurrentAppointments
                                      Where upcoming.User.UserName = Me.Application.User.Name

            For Each item In upcomingAppointment

                If valDate > item.StartTime AndAlso valDate < item.endtime Then
                    Return False
                End If
            Next

            Return True
        End Function
    End Class

End Namespace

